package com.grf.es.highlevelrest;

import java.io.IOException;
import java.util.Map;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

public class Aggregation {
	
	public void test() throws IOException {
		RestHighLevelClient client = Client.getClient();
		SearchRequest searchRequest = new SearchRequest("test3");
		TermsAggregationBuilder aggregation = AggregationBuilders.terms("time").field("timestamp");
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.aggregation(aggregation);
		searchRequest.source(searchSourceBuilder);
		//AggregationBuilders.avg("");
		SearchResponse searchResponse = client.search(searchRequest);
		System.out.println(searchResponse.toString());
	}

	/**
	 * 统计个数
	 */
	public void count() throws IOException {
		AggregationBuilder aggregationBuilder = AggregationBuilders.count("time").field("timestamp");
		RangeQueryBuilder rangeQueryBuilder = QueryBuilders
				.rangeQuery("timestamp")
				.from(2019-12-03,true)
				.to(2019-12-05,true);
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery().must(rangeQueryBuilder);
		RestHighLevelClient client = Client.getClient();
		SearchRequest searchRequest = new SearchRequest("test3");
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.query(boolQueryBuilder).aggregation(aggregationBuilder);

		searchRequest.source(searchSourceBuilder);
		SearchResponse searchResponse = client.search(searchRequest);
		org.elasticsearch.search.aggregations.Aggregation time = searchResponse.getAggregations().getAsMap().get("time");
		//Map<String, Object> metaData = time.getMetaData();
		//System.out.println(metaData.get("time"));
	}

	public static void main(String[] args) throws IOException {
		Aggregation aggregation = new Aggregation();
		//aggregation.test();
		aggregation.count();
	}
}
